import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_widget/custom/custom_appbar.dart';
import 'package:flutter_widget/custom/custom_button.dart';
import 'package:flutter_widget/utils/cache.dart';
import 'package:flutter_widget/utils/platform.dart';
import 'package:path_provider/path_provider.dart';

// ignore: must_be_immutable
class PathProviderPage extends StatefulWidget {
  String name;
  PathProviderPage({Key? key, required this.name}) : super(key: key);
  @override
  _PathProviderPageState createState() => _PathProviderPageState();
}

class _PathProviderPageState extends State<PathProviderPage> {
  String cacheSting = '0';

  @override
  void initState() {
    // 获取缓存
    if (PlatformUtils.isWeb == false) {
      getAppCache(); // path_provider 不支持web平台
    }
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  // 获取缓存的大小
  void getAppCache() {
    CacheUtil.loadApplicationCache().then((value) {
      // 获取到缓存大小
      String _cacheSting = CacheUtil.formatSize(value);
      if (mounted) {
        print('获取到缓存大小' + _cacheSting.toString());
        setState(() {
          cacheSting = _cacheSting;
        });
      }
    });
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppbar(widget.name, Theme.of(context).primaryColor),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("缓存大小$cacheSting"),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: CustomButton(
                onPressed: () async {
                  // 获取缓存
                  Directory directory =
                      await getApplicationDocumentsDirectory();
                  //清楚缓存并重新获取缓存大小
                  CacheUtil.delDir(directory).then(
                    (value) => getAppCache(),
                  );
                },
                content: Text(
                  "清除缓存",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
